package com.example.administrator.szb.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.example.administrator.szb.R;
import com.example.administrator.szb.bean.New_ProvinceBean;
import com.example.administrator.szb.bean.RzBean;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.ChangeStatuUtil;
import com.example.administrator.szb.util.DialogUtil;
import com.example.administrator.szb.util.GetJsonDataUtil;
import com.example.administrator.szb.util.Toasts;
import com.example.zhouwei.library.CustomPopWindow;
import com.google.gson.Gson;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.TResult;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dmax.dialog.SpotsDialog;


/**
 * Created by D N on 2017/9/14.
 * 名片认证（初级认证）界面；
 */

public class MingPianActivity extends TakePhotoActivity {
    @Bind(R.id.mingpian_back)
    ImageView mingpianBack;
    @Bind(R.id.toolbar2)
    Toolbar toolbar2;
    @Bind(R.id.mingpian_addMP)
    ImageView mingpianAddMP;
    @Bind(R.id.mingpian_tjrz)
    Button mingpianTjrz;

    //public static final int TAKE_PHOTO = 1;//启动相机带的Ccde
    protected Uri imageUri;
    TakePhoto take = getTakePhoto();
    //String[] perms = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};//动态申请权限
    @Bind(R.id.mingpian_jgmc)
    EditText mingpianJgmc;
    @Bind(R.id.mingpian_zjh)
    EditText mingpianZjh;

    CustomPopWindow popWindow;//弹出框

    ArrayList<String> ming_pian_info_rz = new ArrayList<String>();//存放用户填入的信息
    String iconPath = "";//从相机或相册中获取的图片路径

    String city_id = "";//地址选择的城市id
    @Bind(R.id.mingpian_dz)
    TextView mingpianDz;

    /**
     * 地址选择器 的省市区的3个集合
     */
    private ArrayList<New_ProvinceBean.DataBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    AlertDialog dialog;//进度条
    InputMethodManager imm;//软键盘
    OptionsPickerView pvOptions;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ming_pian_activity);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        ButterKnife.bind(this);

        SampleApplicationLike.getActivitiesInstance().add(this);
        imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);//软键盘实例
//        mingpianJgmc.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View view, boolean b) {
//                if(!b){
//                    InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
//
//                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);//让软键盘消失
//                }
//            }
//        });
//
//        mingpianZjh.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View view, boolean b) {
//                if(!b){
//                    InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
//
//                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);//让软键盘消失
//                }
//            }
//        });
    }


    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @OnClick({R.id.mingpian_back, R.id.mingpian_addMP, R.id.mingpian_tjrz, R.id.mingpian_dz})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.mingpian_back:
                finish();
                break;
            case R.id.mingpian_addMP:
                // showProgressbar();//显示进度条
                if(imm.isActive()&&getCurrentFocus()!=null){
                    if (getCurrentFocus().getWindowToken()!=null) {
                        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
                showPopupwindow(R.layout.view_popupwindow_picture_choose, R.layout.ming_pian_activity);
                break;
            case R.id.mingpian_tjrz:
                tjrz();//执行提交认证
               // startActivity(new Intent(MingPianActivity.this, MingPianSuccessActivity.class));
                break;
            case R.id.mingpian_dz:
                if(imm.isActive()&&getCurrentFocus()!=null){
                    if (getCurrentFocus().getWindowToken()!=null) {
                        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }

                if (pvOptions != null){
                    if (!pvOptions.isShowing()){
                        addressChoose();
                    }else{

                    }
                }else{
                    addressChoose();
                }

                break;

        }
    }

    /**
     *地址选择框
     */
    private void addressChoose() {
        initJsonData();
        ShowPickerView();
    }


    /**
     * 弹出选择地址框
     */
    private void ShowPickerView() {// 弹出选择器

        pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2) +
                        options3Items.get(options1).get(options2).get(options3);
                mingpianDz.setText(tx);
                //Toasts.show(MingPianActivity.this,tx,Toast.LENGTH_SHORT);

                if (options1Items.get(options1).getNext().get(options2).getNext().get(options3).getAreaname().equals(options3Items.get(options1).get(options2).get(options3))) {
                    city_id = options1Items.get(options1).getNext().get(options2).getNext().get(options3).getId() + "";
                }
            }
        })

                .setTitleText("地址选择")
                .setTitleBgColor(getResources().getColor(R.color.white))
                .setSubmitColor(getResources().getColor(R.color.toolbar_home))
                .setCancelColor(getResources().getColor(R.color.cancel))
                .setLineSpacingMultiplier(3)
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    /**
     * 解析城市数据
     */
    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "New_pro.json");//获取assets目录下的json文件数据
        Gson gson = new Gson();
        New_ProvinceBean new_provinceBean = gson.fromJson(JsonData, New_ProvinceBean.class);

        ArrayList<New_ProvinceBean.DataBean> jsonBean = (ArrayList<New_ProvinceBean.DataBean>) new_provinceBean.getData();//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getNext().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getNext().get(c).getAreaname();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getNext().get(c).getNext() == null
                        || jsonBean.get(i).getNext().get(c).getNext().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getNext().get(c).getNext().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getNext().get(c).getNext().get(d).getAreaname();

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        // mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }

    /**
     * 提交按钮
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void tjrz() {
        //getInfo();//获取用户提交的信息；
        boolean flag = checkInfo();//检查用户信息是否完整；
        if (flag) {
            requestMingPianRZ();
        }
    }

    /**
     * 执行名片认证请求
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void requestMingPianRZ() {
        showProgressbar();//显示进度条
        Map<String, String> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("id", SampleApplicationLike.getUserloginInstance().getId()+"");
        String image_icon = ChangeStatuUtil.bitmapToString(iconPath);
        map.put("business", image_icon);
        map.put("company", ming_pian_info_rz.get(0));
        map.put("work_tel", ming_pian_info_rz.get(1));
        map.put("city_id", ming_pian_info_rz.get(2));
        map.put("particular_city", "杨小刚");

        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, RzBean.class, URLAddress.URLBASE + URLAddress.URL_CJ_RZ, map,
                new Response.Listener() {
                    @Override
                    public void onResponse(Object response) {
                      //  response.toString();
                        RzBean rzBean = (RzBean) response;
                        if (rzBean.getResult() != 1) {
                            dialog.dismiss();
                            DialogUtil.showSimpleDialog(MingPianActivity.this, rzBean.getErr_msg());
                        } else {
                            dialog.dismiss();
                            startActivity(new Intent(MingPianActivity.this, MingPianSuccessActivity.class));
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        dialog.dismiss();
                        Toasts.show(MingPianActivity.this, ""+error.toString(), Toast.LENGTH_SHORT);
                        Toasts.show(MingPianActivity.this, "客官再试一次吧....", Toast.LENGTH_SHORT);
                    }
                });

    }

    /**
     * 显示进度条
     */
    private void showProgressbar() {
        dialog = new SpotsDialog(this, R.style.Custom);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        // WindowManager m = getWindowManager();
//        Display d = m.getDefaultDisplay();  //为获取屏幕宽、高
//        android.view.WindowManager.LayoutParams p = dialog.getWindow().getAttributes();  //获取对话框当前的参数值
//        p.height = 300;   //高度设置为屏幕的0.3
//        p.width = 500;    //宽度设置为屏幕的0.5
//        dialog.getWindow().setAttributes(p);
    }

    /**
     * 检查信息
     *
     * @return
     */
    private boolean checkInfo() {
        getInfo();//first get write info.
        if (TextUtils.isEmpty(ming_pian_info_rz.get(0))) {
            DialogUtil.showSimpleDialog(MingPianActivity.this, "请输入机构名称");
        } else if (TextUtils.isEmpty(ming_pian_info_rz.get(1))) {
            DialogUtil.showSimpleDialog(MingPianActivity.this, "请输入机构座机号");
        } else if (TextUtils.isEmpty(ming_pian_info_rz.get(2))) {
            DialogUtil.showSimpleDialog(MingPianActivity.this, "请输入机构地址");
        } else if (TextUtils.isEmpty(ming_pian_info_rz.get(3))) {
            DialogUtil.showSimpleDialog(MingPianActivity.this, "请选择上传的名片");
        } else {
            return true;
        }

        return false;
    }

    /**
     * 获取填入的信息
     */
    private void getInfo() {
        ming_pian_info_rz.clear();
        ming_pian_info_rz.add(mingpianJgmc.getText().toString().trim());
        ming_pian_info_rz.add(mingpianZjh.getText().toString().trim());

        if (mingpianDz.getText().toString().trim().equals("请输入机构地址")) {
            ming_pian_info_rz.add("");
        } else {
            ming_pian_info_rz.add(city_id);//这里加入地址的id,而不是textview的值
        }

//        Log.e("pdf", "getInfo: "+mingpianAddMP.getDrawable().getCurrent().getConstantState());
//        Log.e("pdf","getInof: "+getResources().getDrawable(R.drawable.tjmp_new).getConstantState());
        if (mingpianAddMP.getDrawable().getCurrent().getConstantState().equals(getResources().getDrawable(R.drawable.add_id_image).getConstantState())) {//判断是不是默认图片
            ming_pian_info_rz.add(null);
        } else {
            // String image_buff = new String(getImageBytes(getBitmapFromPath(iconPath)));
            ming_pian_info_rz.add("has data");
        }
    }


    /**
     * 初始化popupwindow弹出框
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void showPopupwindow(int view_layout_id, int rootview_layout_id) {
        View popwindow_view = LayoutInflater.from(this).inflate(view_layout_id, null);
        View rootview = LayoutInflater.from(this).inflate(rootview_layout_id, null);

        //如果不是进度框，就执行底部弹出
        if (view_layout_id != R.layout.view_progressbar) {
            popWindow = new CustomPopWindow.PopupWindowBuilder(this)
                    .setView(popwindow_view)//显示的布局，还可以通过设置一个View
                    .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                    .setBgDarkAlpha(0.7f) // 控制亮度
                    .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) //设置显示的大小，不设置就默认包裹内容
                    .setFocusable(true)//是否获取焦点，默认为ture
                    .setOutsideTouchable(true)//是否PopupWindow 以外触摸dissmiss
                    .create()//创建PopupWindow
                    .showAtLocation(rootview, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            handleLogic(popwindow_view, popWindow);//处理popupwindow 中的item点击事件
        } else {
            popWindow = new CustomPopWindow.PopupWindowBuilder(this)
                    .setView(popwindow_view)//显示的布局，还可以通过设置一个View
                    .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                    .setBgDarkAlpha(0.7f) // 控制亮度
                    .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) //设置显示的大小，不设置就默认包裹内容
                    .setFocusable(true)//是否获取焦点，默认为ture
                    .setOutsideTouchable(false)//是否PopupWindow 以外触摸dissmiss
                    .create()//创建PopupWindow
                    .showAsDropDown(mingpianJgmc);
            // .showAtLocation(rootview, Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);
        }
        //显示PopupWindow

    }

    /**
     * 处理弹出显示内容、点击事件等逻辑
     *
     * @param contentView
     */
    private void handleLogic(View contentView, final CustomPopWindow mCustomPopWindow) {
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCustomPopWindow != null) {
                    mCustomPopWindow.dissmiss();
                }
                String showContent = "";
                switch (v.getId()) {
                    case R.id.textView26:
                        takePhoto();
                        break;
                    case R.id.textView27:
                        // showContent = "点击 Item菜单2";
                        chooseImage();
                        break;
                    case R.id.textView28:
                        mCustomPopWindow.dissmiss();
                        break;
                }
                //Toasts.show(MingPianActivity.this, showContent, Toast.LENGTH_SHORT);
            }
        };
        contentView.findViewById(R.id.textView26).setOnClickListener(listener);
        contentView.findViewById(R.id.textView27).setOnClickListener(listener);
        contentView.findViewById(R.id.textView28).setOnClickListener(listener);

    }

    /**
     * 开启图片选择
     */
    private void chooseImage() {
       // take.onPickFromGallery();
        CropOptions cropOptions=new CropOptions.Builder().setAspectX(9999).setAspectY(9998).setWithOwnCrop(false).create();
        take.onPickFromGalleryWithCrop(getImageUri(),cropOptions);
    }


    /**
     * 开启相机拍照
     */
    public void takePhoto() {
        //take.onPickFromCapture(getImageUri());//执行拍照
        CropOptions cropOptions=new CropOptions.Builder().setAspectX(9999).setAspectY(9998).setWithOwnCrop(false).create();
        take.onPickFromCaptureWithCrop(getImageUri(),cropOptions);
    }


    /**
     * 拍照或者从相片选取相片的回调方法
     *
     * @param result
     */
    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        iconPath = result.getImage().getOriginalPath();
        Glide.with(this).load(new File(iconPath)).into(mingpianAddMP);
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }

    @Override
    public void takeCancel() {
        super.takeCancel();
    }

//    /**
//     * 执行打开相机方法
//     */
//    public void take_photo() {
//        //检查权限(6.0以上做权限判断)
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            if (EasyPermissions.hasPermissions(MingPianActivity.this, perms)) {
//                take_photo_other();
//                //startPermissionsActivity();
//            }
//            else {
//                //第二个参数是被拒绝后再次申请该权限的解释
//                //第三个参数是请求码
//                //第四个参数是要申请的权限
//                EasyPermissions.requestPermissions(MingPianActivity.this, "拍照必要的权限", TAKE_PHOTO, perms);
//            }
//        } else {
//            take_photo_other();
//        }
//    }

    //将bitmap转成字节数组

    /**
     * 返回一个Uri给take调用
     */
    public Uri getImageUri() {
        File file = getImgFile();
        imageUri = Uri.fromFile(file);
        return imageUri;

    }

    /**
     * 设置文件存储路径，返回一个file
     *
     * @return
     */
    private File getImgFile() {
        File file = new File(Environment.getExternalStorageDirectory() + "/szb/image");
        if (!file.exists()) {
            //要点！
            file.mkdirs();
        }
        File imgFile = new File(file, "image"+System.currentTimeMillis()+".jpg");
        return imgFile;

    }

}
